from google.appengine.api import urlfetch
from appengine_utilities import sessions
from google.appengine.api import channel
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import images
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from astarclasses import *
from datetime import datetime
from string import Template
import string
from string import *
import cgi
import os
import logging
import sys
import time # to sleep
from django.utils import simplejson as json
import re

from astarutils import * # this defines helpful functions like friendly date delta format

class ChannelConnectHandler(webapp.RequestHandler):
  def post(self):
    ChangeCount("/total_star_count", 1) # add one to the counter of how many stars there are


class ChannelDisconnectHandler(webapp.RequestHandler):
  def post(self):
  	ChangeCount("/total_star_count", -1) # subtract one from the counter of how many stars there are
  	logging.debug("disconnected channel from %s" % self.request.get("from"))
    ##handle_disconnection(self.request.get('from'))
    
class GetDemographics(webapp.RequestHandler):
	def get(self):
		talk_key = self.request.get("talk_key")
		
		#num_males = GetCount("/%s/males" % talk_key)
		#num_females = GetCount("/%s/females" % talk_key)
		#num_category1 = GetCount("/%s/category1" % talk_key)
		#num_category2 = GetCount("/%s/category2" % talk_key)
		#num_category3 = GetCount("/%s/category3" % talk_key)
		#num_age_entries = GetCount("/%s/num_age_entries" % talk_key)
		#sum_of_all_ages = GetCount("/%s/sum_of_all_ages" % talk_key)
		# fix any negative count values
		#if num_category1 < 0: ChangeCount("/%s/category1" % talk_key, -num_category1)
		#if num_category2 < 0: ChangeCount("/%s/category2" % talk_key, -num_category2)
		#if num_category3 < 0: ChangeCount("/%s/category3" % talk_key, -num_category3)
		try:
			talk = Talk.get(talk_key)
		except:
			talk = None
		if talk:
			stars = Star.gql("WHERE ANCESTOR IS :1", talk)
		num_males = num_females = num_category1 = num_category2 = num_category3 = 0
		for star in stars:
			if star.sex == "M": num_males +=1
			if star.sex == "F": num_females += 1
			if star.category == 1: num_category1 += 1
			if star.category == 2: num_category2 += 1
			if star.category == 3: num_category3 += 1 
		message = json.dumps({'message':'demographics', 'num_males':num_males, 'num_females':num_females,
							  'num_category1': num_category1, 'num_category2': num_category2,
							  'num_category3': num_category3})
		self.response.out.write(message)
			

class SetStar(webapp.RequestHandler):		
	def post(self):
		display_name = self.request.get("display_name")
		welcome_message = None # if we get a valid name change, we'll send a welcome message
		# check for "naughty words" in the display name
		display_name = re.sub("shit|fuck|bloody|bastard|wanker|penis|cunt|bitch|cocksucker|blowhard|sucker|banger(?i)", "*", display_name)
		display_name = display_name.strip()
		display_name = display_name[:32] # limit names to at most 32 characters
		sex = self.request.get("gender")
		work = self.request.get("work")
		try:
			work = int(work)
		except:
			work = 0
		age = self.request.get("age")
		try:
			age = int(age)
		except:
			age = 0
		
		
		self.sess = sessions.Session() # get the unique session id to identify this client
		star = None # begin by assuming that no user (star) has been created for this session
		if self.sess.has_key("star_key"): # try to find a star associated with this session
			star = Star.get(self.sess["star_key"])
		if star:
			talk_key = str(star.talk.key())
			if (display_name != ""):
				if (star.display_name != display_name): # if we are changing to a new name
					welcome_message = json.dumps({'message':'welcome', 'welcome_text':"Hello, %s!" % display_name})
					star.display_name = display_name
				else:
					welcome_message = None # if display_name is blank, don't send a welcome message
			if (sex != "" and sex != star.sex): # if the value of sex is changing...
				male_delta = female_delta = 0
				if (sex == "F"): # if star is changing to female
					female_delta = 1 # count one more female
					if (star.sex == "M"): # if star used to be male
						male_delta = -1 # subtract one from male count
				if (sex == "M"): 
					male_delta = 1
					if (star.sex == "F"):
						female_delta = -1
				# update the counters
				ChangeCount("/%s/males" % talk_key, male_delta)
				ChangeCount("/%s/females" % talk_key, female_delta)
				# store the change in the star entity
				star.sex = sex
				
			if (work != 0):
				cat1_delta = cat2_delta = cat3_delta = 0
				if (work != star.category): # if the star's work category is changing
					if (work == 1):
						cat1_delta = 1
						if (star.category==2):
							cat2_delta = -1
						if (star.category==3):
							cat3_delta = -1
					if (work == 2):
						cat2_delta = 1
						if (star.category==1):
							cat1_delta = -1
						if (star.category==3):
							cat3_delta = -1
					if (work == 3):
						cat3_delta = 1
						if (star.category==1):
							cat1_delta = -1
						if (star.category==2):
							cat2_delta = -1
					if (cat1_delta != 0): ChangeCount("/%s/category1" % talk_key, cat1_delta)
					if (cat2_delta != 0): ChangeCount("/%s/category2" % talk_key, cat2_delta)
					if (cat3_delta != 0): ChangeCount("/%s/category3" % talk_key, cat3_delta)
					star.category = work
			if (age > 10 and age < 90):
				star.age = age
			star.put()
			# notify the presenter
			star_update = {'key':str(star.key()),
						   'display_name': star.display_name,
						   'category': str(star.category)}
			
			message = json.dumps({'message':'star_update', 'star':star_update})
					
			connected_presenters_query = db.GqlQuery("SELECT __key__ FROM Presenter WHERE ANCESTOR IS :1", star.parent())
			num_presenters=0
			for connected_presenter_key in connected_presenters_query:
				try:
					if welcome_message:
						channel.send_message("presenter-"+str(connected_presenter_key.id()),message)
					num_presenters +=1
				except:
					pass
			if welcome_message:
				self.response.out.write(welcome_message) # send json welcome message to user
						

	
application = webapp.WSGIApplication([('/star/set', SetStar),
									  ('/star/getdemographics', GetDemographics),
									  ('/_ah/channel/disconnected/ ', ChannelDisconnectHandler),
									  ('/_ah/channel/connected/',  ChannelConnectHandler),
					  ],
				     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
